<template>
    <view class="container">
      <view class="title">选择教练</view>
      
      <view v-if="!enrollment" class="enrollment-tip card">
        <text>您还没有完成报名流程</text>
        <button class="btn-primary" size="mini" @click="navigateTo('/pages/enrollment/apply/apply')">立即报名</button>
      </view>
      
      <block v-else>
        <view class="enrollment-info card">
          <view class="info-item">
            <text class="info-label">报名状态：</text>
            <text class="info-value" :class="getStatusClass(enrollment.status)">
              {{ getStatusText(enrollment.status) }}
            </text>
          </view>
          <view class="info-item">
            <text class="info-label">驾照类型：</text>
            <text class="info-value">{{ getLicenseTypeText(enrollment.license_type) }}</text>
          </view>
          <view class="info-item" v-if="enrollment.coach_id">
            <text class="info-label">当前教练：</text>
            <text class="info-value">{{ currentCoachName }}</text>
          </view>
        </view>
        
        <!-- 搜索筛选 -->
        <view class="filter-container">
          <view class="search-box">
            <input 
              class="search-input" 
              type="text" 
              v-model="searchKeyword" 
              placeholder="搜索教练姓名" 
              @input="handleSearch"
            />
            <text class="search-icon">🔍</text>
          </view>
          
          <view class="filter-options">
            <picker 
              mode="selector" 
              :range="licenseTypeOptions" 
              range-key="label" 
              :value="licenseTypeIndex" 
              @change="handleLicenseTypeChange"
            >
              <view class="filter-item">
                <text>驾照类型：</text>
                <text>{{ licenseTypeOptions[licenseTypeIndex].label }}</text>
              </view>
            </picker>
            
            <picker 
              mode="selector" 
              :range="sortOptions" 
              range-key="label" 
              :value="sortIndex" 
              @change="handleSortChange"
            >
              <view class="filter-item">
                <text>排序：</text>
                <text>{{ sortOptions[sortIndex].label }}</text>
              </view>
            </picker>
          </view>
        </view>
        
        <!-- 教练列表 -->
        <view class="coach-list">
          <view v-if="filteredCoaches.length === 0" class="empty-tip">
            暂无符合条件的教练
          </view>
          
          <view 
            class="coach-item card" 
            v-for="(item, index) in filteredCoaches" 
            :key="index"
            @click="viewCoachDetail(item)"
          >
            <view class="coach-avatar">
              <image :src="item.avatar || '/static/images/default-avatar.png'" mode="aspectFill"></image>
            </view>
            
            <view class="coach-info">
              <view class="coach-name">{{ item.real_name }}</view>
              <view class="coach-meta">
                <text class="coach-license">可教：{{ formatLicenseTypes(item.license_types) }}</text>
                <text class="coach-experience">教龄：{{ item.experience_years }}年</text>
              </view>
              <view class="coach-stats">
                <view class="rating">
                  <text class="rating-text">评分：</text>
                  <text class="rating-value">{{ item.rating }}</text>
                  <text class="rating-star" v-for="n in 5" :key="n">
                    {{ n <= Math.round(item.rating) ? '★' : '☆' }}
                  </text>
                </view>
                <text class="coach-students">学员：{{ item.current_students }}/{{ item.max_students }}</text>
              </view>
              <view class="coach-status" :class="getCoachStatusClass(item.status)">
                {{ getCoachStatusText(item.status) }}
              </view>
            </view>
            
            <view class="coach-action">
              <button 
                class="btn-select" 
                :disabled="!canSelectCoach(item)" 
                @click.stop="selectCoach(item)"
              >
                {{ enrollment.coach_id === item.id ? '已选择' : '选择' }}
              </button>
            </view>
          </view>
        </view>
      </block>
    </view>
  </template>
  
  <script>
  import { mapActions, mapGetters } from 'vuex';
  import * as api from '@/api/coach';
  import config from '@/config/index';
  
  export default {
    data() {
      return {
        coaches: [],
        searchKeyword: '',
        licenseTypeOptions: [
          { value: '', label: '全部类型' },
          ...config.licenseTypes
        ],
        licenseTypeIndex: 0,
        sortOptions: [
          { value: 'rating', label: '评分优先' },
          { value: 'experience', label: '教龄优先' },
          { value: 'students', label: '学员数少优先' }
        ],
        sortIndex: 0,
        currentCoachName: ''
      };
    },
    computed: {
      ...mapGetters('enrollment', [
        'currentEnrollment'
      ]),
      enrollment() {
        return this.currentEnrollment;
      },
      filteredCoaches() {
        let result = [...this.coaches];
        
        // 关键词搜索
        if (this.searchKeyword) {
          result = result.filter(item => 
            item.real_name.includes(this.searchKeyword)
          );
        }
        
        // 驾照类型筛选
        const licenseType = this.licenseTypeOptions[this.licenseTypeIndex].value;
        if (licenseType) {
          result = result.filter(item => 
            item.license_types.includes(licenseType)
          );
        }
        
        // 排序
        const sortBy = this.sortOptions[this.sortIndex].value;
        if (sortBy === 'rating') {
          result.sort((a, b) => b.rating - a.rating);
        } else if (sortBy === 'experience') {
          result.sort((a, b) => b.experience_years - a.experience_years);
        } else if (sortBy === 'students') {
          result.sort((a, b) => (a.current_students / a.max_students) - (b.current_students / b.max_students));
        }
        
        return result;
      }
    },
    onLoad() {
      // 获取当前报名信息
      if (!this.enrollment) {
        this.getMyEnrollments();
      }
      
      // 获取教练列表
      this.loadCoaches();
    },
    methods: {
      ...mapActions('enrollment', [
        'getMyEnrollments',
        'getEnrollment',
        'selectCoach'
      ]),
      navigateTo(url) {
        uni.navigateTo({
          url
        });
      },
      loadCoaches() {
        uni.showLoading({
          title: '加载中...'
        });
        
        api.getCoaches()
          .then(res => {
            this.coaches = res.data;
            
            // 如果有选择的教练，获取教练姓名
            if (this.enrollment && this.enrollment.coach_id) {
              const coach = this.coaches.find(item => item.id === this.enrollment.coach_id);
              if (coach) {
                this.currentCoachName = coach.real_name;
              }
            }
          })
          .catch(err => {
            this.showToast(err.message || '获取教练列表失败');
          })
          .finally(() => {
            uni.hideLoading();
          });
      },
      handleSearch() {
        // 搜索功能已通过计算属性实现
      },
      handleLicenseTypeChange(e) {
        this.licenseTypeIndex = e.detail.value;
      },
      handleSortChange(e) {
        this.sortIndex = e.detail.value;
      },
      getStatusText(status) {
        const statusMap = {
          'pending': '待审核',
          'reviewing': '审核中',
          'approved': '已通过',
          'rejected': '已拒绝'
        };
        return statusMap[status] || status;
      },
      getStatusClass(status) {
        const classMap = {
          'pending': 'status-pending',
          'reviewing': 'status-reviewing',
          'approved': 'status-approved',
          'rejected': 'status-rejected'
        };
        return classMap[status] || '';
      },
      getLicenseTypeText(type) {
        const license = config.licenseTypes.find(item => item.value === type);
        return license ? license.label : type;
      },
      formatLicenseTypes(types) {
        if (!types) return '';
        
        // 如果是字符串，先转成数组
        const typeArray = typeof types === 'string' ? types.split(',') : types;
        
        return typeArray.join(', ');
      },
      getCoachStatusText(status) {
        const statusMap = {
          'active': '可预约',
          'inactive': '不可预约',
          'on_leave': '请假中'
        };
        return statusMap[status] || status;
      },
      getCoachStatusClass(status) {
        const classMap = {
        'active': 'coach-active',
        'inactive': 'coach-inactive',
        'on_leave': 'coach-on-leave'
      };
      return classMap[status] || '';
    },
    canSelectCoach(coach) {
      // 判断是否可以选择教练
      if (!this.enrollment || this.enrollment.status !== 'approved') {
        return false;
      }
      
      if (coach.status !== 'active') {
        return false;
      }
      
      if (coach.current_students >= coach.max_students) {
        return false;
      }
      
      // 如果已经选择了这个教练，不能再次选择
      if (this.enrollment.coach_id === coach.id) {
        return false;
      }
      
      // 判断教练是否可以教授此类型驾照
      const typeArray = typeof coach.license_types === 'string' ? 
        coach.license_types.split(',') : coach.license_types;
      
      return typeArray.includes(this.enrollment.license_type);
    },
    viewCoachDetail(coach) {
      // 查看教练详情
      uni.navigateTo({
        url: `/pages/coach/detail?id=${coach.id}`
      });
    },
    selectCoach(coach) {
      if (!this.canSelectCoach(coach)) return;
      
      this.showModal(`确认选择 ${coach.real_name} 作为您的教练吗？`)
        .then(confirm => {
          if (confirm) {
            uni.showLoading({
              title: '处理中...'
            });
            
            this.selectCoach({
              enrollmentId: this.enrollment.id,
              coachId: coach.id
            })
              .then(() => {
                this.showToast('选择教练成功', 'success');
                this.currentCoachName = coach.real_name;
                // 重新获取报名信息
                this.getEnrollment(this.enrollment.id);
              })
              .catch(err => {
                this.showToast(err.message || '选择教练失败');
              })
              .finally(() => {
                uni.hideLoading();
              });
          }
        });
    }
  }
};
</script>

<style lang="scss">
.container {
  padding: 30rpx;
}

.title {
  font-size: 36rpx;
  font-weight: bold;
  text-align: center;
  margin-bottom: 40rpx;
}

.enrollment-tip {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  margin-bottom: 30rpx;
}

.enrollment-info {
  margin-bottom: 30rpx;
  padding: 30rpx;
}

.info-item {
  display: flex;
  margin-bottom: 20rpx;
}

.info-label {
  width: 160rpx;
  font-size: 28rpx;
  color: #666;
}

.info-value {
  flex: 1;
  font-size: 28rpx;
}

.status-pending {
  color: #e6a23c;
}

.status-reviewing {
  color: #409eff;
}

.status-approved {
  color: #67c23a;
}

.status-rejected {
  color: #f56c6c;
}

.filter-container {
  margin-bottom: 30rpx;
}

.search-box {
  position: relative;
  margin-bottom: 20rpx;
}

.search-input {
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  padding: 0 80rpx 0 20rpx;
  font-size: 28rpx;
  color: #333;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  box-sizing: border-box;
}

.search-icon {
  position: absolute;
  right: 20rpx;
  top: 20rpx;
  font-size: 40rpx;
  color: #999;
}

.filter-options {
  display: flex;
  justify-content: space-between;
}

.filter-item {
  display: flex;
  align-items: center;
  font-size: 28rpx;
  padding: 20rpx 0;
}

.coach-list {
  margin-bottom: 40rpx;
}

.empty-tip {
  text-align: center;
  padding: 60rpx 0;
  color: #999;
}

.coach-item {
  display: flex;
  padding: 30rpx;
  margin-bottom: 20rpx;
  position: relative;
}

.coach-avatar {
  width: 120rpx;
  height: 120rpx;
  margin-right: 20rpx;
}

.coach-avatar image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.coach-info {
  flex: 1;
}

.coach-name {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
}

.coach-meta {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.coach-stats {
  display: flex;
  justify-content: space-between;
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.rating {
  display: flex;
  align-items: center;
}

.rating-value {
  color: #ff9800;
  margin-right: 10rpx;
}

.rating-star {
  color: #ff9800;
  font-size: 20rpx;
}

.coach-status {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  font-size: 24rpx;
  padding: 4rpx 16rpx;
  border-radius: 20rpx;
}

.coach-active {
  background-color: #e6f7f0;
  color: #52c41a;
}

.coach-inactive {
  background-color: #f0f0f0;
  color: #999;
}

.coach-on-leave {
  background-color: #fff3f3;
  color: #f56c6c;
}

.coach-action {
  position: absolute;
  bottom: 30rpx;
  right: 30rpx;
}

.btn-select {
  width: 160rpx;
  height: 70rpx;
  line-height: 70rpx;
  font-size: 28rpx;
  color: #fff;
  background-color: #3c8dbc;
  border-radius: 6rpx;
}

.btn-select[disabled] {
  background-color: #ddd;
  color: #999;
}

.btn-primary {
  color: #fff;
  background-color: #3c8dbc;
}
</style>